/*
 * @Author: your name
 * @Date: 2021-12-23 09:20:01
 * @LastEditTime: 2022-02-06 11:08:42
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vue\vue-douban-rd\routes\users.js
 */
const jwt = require('jsonwebtoken');
const router = require('koa-router')()
const db = require('./db')
let mySecretKey = "asdsahjgbsdgkasdiouwerppppsadjk";

// router.prefix('/users')
//登录接口
router.post("/login", async (ctx) => {
  //1.接收数据
  let { username, password } = ctx.request.body;//post方式传参
  //2.验证
  if (username == '' || password == '') {
    ctx.body = "用户名或密码必须填写!"
  } else {
    //3.连接数据库

    let sql = "SELECT * FROM t_user WHERE username=? and password=?";
    let result = await db.query(sql, [username, password]);

    if (result.length > 0) {
      //生成 token
      let payload = {
        userId: result[0].user_id
      };
      let users = {
        username: result[0].username,
        user_id: result[0].user_id,
        admin: result[0].admin
      }
      let token = jwt.sign(payload, mySecretKey, { expiresIn: 60 });



      ctx.body = {
        code: 2200,
        data: {
          state: "success",
          token,
          users
        }
      }

      // } catch (err) {
      //   ctx.body = {
      //     code: 2401
      //   }
      // }

    } else {
      ctx.body = {
        code: 2200,
        data: {
          state: "fail"
        }
      }
    }

  }
});
router.get("/token", async (ctx) => {
  //拉取请求头中的 token
  try {
    let token = ctx.header.authorization;
    jwt.verify(token, mySecretKey);
    ctx.body = {
      code: 2200,
      data : {
        text: "有token"
      }
    }
  } catch(err) {
    ctx.body = {
      code: 1401,
    }
  }
})
//注册接口
router.post('/register', async (ctx) => {
  //接收数据
  let { username, password, phone, email } = ctx.request.body;
  // let portrait = "uploads/person_1.jpg";
  //验证信息是否填写
  if (username == '' || password == '' || phone == '' || email == '') {
    ctx.body = "请确保全部填写!"
  } else {
    //验证用户是否存在
    let sql = "SELECT * FROM t_user WHERE username=?"
    let result = await db.query(sql, [username]);
    if (result.length > 0) {
      ctx.body = {
        code: 2200,
        data: {
          state: "repeat",
        }
      }
    } else {
      //连接数据库
      //将用户信息插入数据库
      let sql = "INSERT INTO t_user(username, password, phone, email) VALUES(?,?,?,?)";
      let result = await db.query(sql, [username, password, phone, email]);
      if (result.affectedRows > 0) {
        ctx.body = {
          code: 2200,
          data: {
            state: "success"
          }
        }
      } else {
        ctx.body = {
          code: 2500,
          data: {
            state: "fail"
          }
        }
      }
    }

  }
})
router.post("/updateInfo", async (ctx) => {
  let { username, phone, email, userId } = ctx.request.body
  let sql = "UPDATE t_user SET username=?, phone=?, email=? WHERE user_id=?"
  await db.query(sql, [username, phone, email, userId])
})
router.post("/pwUpdate", async (ctx) => {
  let { username, password, newpassword, userId } = ctx.request.body
  let sql = "SELECT * FROM t_user WHERE username=?"
  let result = await db.query(sql, [username])
  let sql1 = "SELECT * FROM t_user WHERE password=?"
  let result1 = await db.query(sql1, [password])
  let sql2 = "UPDATE t_user SET password=? WHERE user_id=?"
  if (result.length > 0) {
    if (result1.length > 0) {
      await db.query(sql2, [newpassword, userId])
      ctx.body = {
        code: 2200,
        data: {
          state: "success"
        }
      }
    } else {
      ctx.body = {
        code: 2500,
        data: {
          state: "fail"
        }
      }
    }
  } else {
    ctx.body = {
      code: 2500,
      data: {
        state: "fail"
      }
    }
  }
})
router.post("/setAdmin", async (ctx) => {
  let { val = 1, userId } = ctx.request.body
  let sql = "UPDATE t_user SET admin=? WHERE user_id=?"
  let result = await db.query(sql, [val, userId])
  let sql1 = "SELECT admin FROM t_user WHERE user_id=?"
  let result1 = await db.query(sql1, [userId])
  if (result1[0].admin == 1) {
    ctx.body = {
      code: 2200,
      data: {
        state: "success"
      }
    }
  } else {
    ctx.bode = {
      code: 2500,
      data: {
        state: "fail"
      }
    }
  }
})
router.post("/deleteAdmin", async (ctx) => {
  let { val = "", userId } = ctx.request.body
  let sql = "UPDATE t_user SET admin=? WHERE user_id=?"
  await db.query(sql, [val, userId])
  let sql1 = "SELECT admin FROM t_user WHERE user_id=?"
  let result = await db.query(sql1, [userId])
  if (result[0].admin == 0) {
    ctx.body = {
      code: 2200,
      data: {
        state: "success"
      }
    }
  } else {
    ctx.body = {
      code: 2500,
      data: {
        state: "fail"
      }
    }
  }
})

module.exports = router
